# -*- coding: utf-8 -*-
"""
Created on Thu Nov 25 20:12:32 2021

@author: bwm
"""
import pandas as pd
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import statistics

class output:#（待完成）
    def __init__(self,my_history):
        
        self.my_history = my_history
    def get_plot(self):#主要需要完成这里的画图
        # 可视化（收益率画图），一个dataframe可以画折线图
        plt.figure(figsize=(8, 6), dpi=80, facecolor='white')

        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        date_list = self.my_history.return_history.index.tolist()
        ax = plt.gca()
        return_list = self.my_history.return_history.values.tolist()
        import itertools
        return_list = list(itertools.chain.from_iterable(return_list))
        new_return_list = []
        for item in return_list:
            new_item = float(item) * 100
            new_return_list.append(new_item)

        ##导入指数的数据
        index_data = pd.read_excel("./000001sh.xlsx", header=0)  ##读入大盘十年的数据
        index_data = index_data.set_index("时间", inplace=False)
        index_dict = {}

        for item in date_list:
            data_one = index_data.loc[item, "Close"]
            index_dict[item] = data_one
        #print(index_dict)
        index_change=[0]
        for i in range(1,len(date_list)):
            date=date_list[i]
            #print(date)
            date_first=date_list[0]
            #print(date_first)
            current_level=index_dict[date]
            #print(current_level)
            initial_level=index_dict[date_first]
            #print(initial_level)
            change=(current_level/initial_level-1)*100
            index_change.append(change)
        #print(index_change)

        plt.title(" 策略回测结果 ", fontsize=20)
        plt.xlabel('date', fontsize=15, loc='right')
        plt.ylabel('income ratio (%)', fontsize=15, loc='top')
        plt.plot(date_list, new_return_list, c='r',label='策略收益')
        plt.plot(date_list, index_change, c='b',label='上证指数收益')
        plt.xticks(rotation=90)
        plt.grid(axis="y", linestyle="--")
        plt.legend(loc='best')
        ax.xaxis.set_major_locator(ticker.MultipleLocator(30))  # 日期的间隔
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)

        st_dev = statistics.pstdev(return_list)
        r_f = statistics.mean(index_change)
        sharp_ratio = (new_return_list[-1] - r_f) / st_dev/100
        sharp_ratio= round(sharp_ratio, 2)
        copylist = new_return_list.copy()
        copylist.sort()
        max_ratio = copylist[-1]
        max_ratio=round(max_ratio, 2)
        min_ratio = copylist[0]
        min_ratio=round(min_ratio, 2)
        sharp_text='夏普比率是：'+' '+str(sharp_ratio)
        max_text='最大收益率是：'+' '+str(max_ratio)+'%'
        min_text='最小收益率是：'+' '+str(min_ratio)+'%'
        income_text='策略收益率是：'+''+str(round(new_return_list[-1],2))+'%'
        plt.text(0, 120, sharp_text)
        # plt.text(200, 120, sharp_ratio)
        plt.text(0, 115, max_text)
        # plt.text(200, 115, max_ratio)
        # plt.text(0, 110, "最小收益率是：")
        # plt.text(200, 110, min_ratio)
        plt.text(0, 110, min_text)
        plt.text(0, 105, income_text)
        # plt.text(200, 105, round(new_return_list[-1],2))
        # plt.text(235, 105, "%")

        plt.show()


        return 
    
    def get_order_history(self):#会给一个list，list里每条记录一条交易信息[‘2021-10-12’,’600001’,’20’,’100’,’买’]
        #交易订单信息输出dataframe
        oh=self.my_history.order_history
        df = pd.DataFrame(oh, columns=['Date', 'Ticker', 'Volume', 'Price', 'Buy_or_Sell'])
        outputpath_1 = './history_order.xlsx'
        df.to_excel(outputpath_1, index=True, header=True)
        return
    
    def get_hold_histroy(self):#会给个dataframe，会记录日期、现金、股票、总价值
        #每日持仓信息dataframe（日期、现金、股票代码及数量）
        outputpath_2 = './history_hold.xlsx'
        hh=self.my_history.hold_history
        hh.to_excel(outputpath_2, index=True, header=True)
        return